package main

import (
	"fmt"
	"log"
	"math/rand"
	"sync"
	"time"
)

type People struct{ name string }

func (p *People) read() {
	fmt.Println(p.name)
}

func (p *People) write(n string) {
	p.name = n
	fmt.Println("write", p.name)
}

func mutiRead() {
	// 多个goroutine读不需要锁
	p := &People{name: "lilei"}
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			p.read()
			wg.Done()
		}()
	}
	wg.Wait()
}

func mutiWrite() {
	// 多个goroutine写需要锁
	p := &People{name: "lilei"}
	var wg sync.WaitGroup
	var mu sync.Mutex
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			mu.Lock()
			defer mu.Unlock()
			p.write("yl")
			wg.Done()
		}()
	}
	wg.Wait()
}

func mutiWriteRead() {
	// 一个goroutine写，多个读需要锁
	p := &People{name: "lilei"}
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			if i == 0 {
				p.write("yl")
			} else {
				p.read()
			}

			wg.Done()
		}()
	}
	wg.Wait()
}

// 读取数组不同位置不需要锁
func readSlice() {
	s := make([]int, 0)
	for i := 0; i < 10; i++ {
		s = append(s, i)
	}
	var wg sync.WaitGroup
	for j := 0; j < 5; j++ {
		wg.Add(1)
		go func(i int) {

			fmt.Println(s[i])
			wg.Done()
		}(j)
	}
	wg.Wait()

}

func s() {
	rand.Seed(86)
	fmt.Println(rand.Intn(100))
	fmt.Println(rand.Intn(100))
	fmt.Println(rand.Intn(100))
}
func main() {
	// a := make([]int, 0)

	// fmt.Println(a[-1:])
	go s()
	go s()
	go s()
	time.Sleep(time.Second)
	log.Fatalf("%d", 1)

}
